//
//  FavoriteListViewController.m
//  reacticons
//
//  Created by Nong Nghia on 6/22/12.
//  Copyright (c) 2012 __MyCompanyName__. All rights reserved.
//

#import "FavoriteListViewController.h"
#import "AppDelegate.h"
#import "ImageDetailViewController.h"
#import "UIGridViewCell+DownloadImage.h"
#import "Utilities.h"
#import "PopUpViewController.h"
#import "MemeCreatorViewController.h"

#import "Photo.h"
#import "DatabaseConnection.h"
#import "LoadingView.h"
#import "DownloadHelper.h"
#import "Globals.h"
#import <QuartzCore/QuartzCore.h>

#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v)  ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)

@interface FavoriteListViewController ()

@end

@implementation FavoriteListViewController

@synthesize parentID = _parentID;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

/*
 // Implement loadView to create a view hierarchy programmatically, without using a nib.
 - (void)loadView
 {
 }
 */

-(void)configureView{
    [myGridView setEnableMultipleSelection:NO];
    imageListArray = [[DatabaseConnection getFavoritePhotos] retain];
    [self downloadAllPhotos];
    DBLOG(@"%d",imageListArray.count);
    self.navigationItem.title=[NSString stringWithFormat:@"Favorites (%d)",imageListArray.count];
    
    
    if (myGridView) {
        [myGridView removeFromSuperview];
        [myGridView release];
        myGridView = nil;
    }
    
    myGridView = [[UIGridView alloc] initWithFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
    
    [myGridView setDelegate:self];
    [myGridView setDataSource:self];
    
    [self.view insertSubview:myGridView atIndex:0];
    
  
    [Utilities showTabBar:nil];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    DBLOG(@"ViewWillAppear");
    [self configureView];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlackOpaque];
}
-(void)viewDidAppear:(BOOL)animated{
    [super viewDidAppear:animated];
    DBLOG(@"ViewDidAppear");
    [self configureView];


}

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
    [super viewDidLoad];
    [self.navigationController.navigationBar setBarStyle:UIBarStyleBlack];
    DBLOG(@"viewdidload");

    UIBarButtonItem * editFavorites = [[UIBarButtonItem alloc] initWithTitle:@"Select" 
                                                                       style:UIBarButtonItemStyleBordered 
                                                                      target:self 
                                                                      action:@selector(btnWasClicked:)];
    editFavorites.tag=EditButtonTag;
    
    
    [self.navigationItem setRightBarButtonItem:editFavorites];
    isMultipleSelection = NO;
    [editFavorites release];
    
    [editBar setHidden:YES];
    [cancelNavBar setHidden:YES];
    
    popUpBar = [[PopUpViewController alloc] init];
    [popUpBar.view setFrame:CGRectMake(0, 0, 72, 34)];
    [popUpBar.view setHidden:YES];
    [popUpBar setDelegate:self];
    [self.view addSubview:popUpBar.view];
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - Grid View Data Source

- (NSInteger)numberOfCellsInGridView:(UIGridView *)gridView
{
    return [imageListArray count];
}

- (CGFloat)gridView:(UIGridView *)gridView heightForRowAtIndex:(NSInteger)rowIndex
{
    return 100;
}

- (NSInteger)gridView:(UIGridView *)gridView numberOfCellsPerRowInRow:(NSInteger)rowIndex
{
    return 3;
}

- (GridViewCell*)gridView:(UIGridView *)gridView cellAtIndex:(NSInteger)cellIndex
{
    UIGridViewCell_DownloadImage * cell = [[[UIGridViewCell_DownloadImage alloc] initWithFrame:CGRectZero] autorelease];
    
    if ([imageListArray count] == 0) {
        return nil;
    }
    Photo * photo = [imageListArray objectAtIndex:cellIndex];
    [cell setImageURLString:photo.photoThumbnail];
    if (listSelected) {
        for (NSNumber *index in listSelected) {
            if ([index intValue]==cellIndex) {
                [cell setAccessoryType:UIGridViewCellAccessorySelected];
                [cell setIsSelected:YES];
                break;
            }
            else
            {
                [cell setAccessoryType:UIGridViewCellAccessoryNone];
                [cell setIsSelected:NO];
            }
        }
    }
    [cell.imageView setContentMode:UIViewContentModeScaleAspectFit];
    [cell.textLabel setHidden:YES];
    
    return cell;
}

#pragma mark - Grid View Delegate

- (void)gridView:(UIGridView *)gridView didSelectedCellAtIndex:(NSInteger)cellIndex
{
    if (!isMultipleSelection) {
        
        CGPoint offsetPoint = gridView.contentOffset;
        
        CGRect frame = [[myGridView cellAtIndex:cellIndex] frame];
        
        [popUpBar setSelectedFrame:CGRectMake(frame.origin.x - offsetPoint.x, 
                                              frame.origin.y - offsetPoint.y, 
                                              frame.size.width, 
                                              frame.size.height)];
        
        [popUpBar setStatusOfFavoriteButtonAsActive:YES];
        if (selectedCellIndex == cellIndex)
        {
            [popUpBar.view setHidden:!popUpBar.view.hidden];
        }
        else {
            [popUpBar.view setHidden:NO];
        }
        selectedCellIndex = cellIndex;

        [[UIPasteboard generalPasteboard] setImage:[self imageAtIndex:selectedCellIndex]];

        
    
        
        
    }
    else {
        BOOL isAdd=NO;
        for (int i=0;i<listSelected.count;i++) {
            if ([[listSelected objectAtIndex:i] intValue]==cellIndex) {
                [[myGridView cellAtIndex:cellIndex] setIsSelected:NO];
                [listSelected removeObjectAtIndex:i];
                isAdd=YES;
                break;
            }
        }
        if (!isAdd) {
            [listSelected addObject:[NSNumber numberWithInt:cellIndex]];
        }
        
        if ([listSelected count]>5) {
            [copyBtn setTitle:@"Copy"];
            [copyBtn setEnabled:NO];
        }
        else {
            [copyBtn setEnabled:YES];
            if (listSelected.count>0) {
                [copyBtn setTitle:[NSString stringWithFormat:@"Copy (%d)",listSelected.count]];
            }
            else {
                [copyBtn setTitle:@"Copy"];
            }
        }
        textlb.title=[NSString stringWithFormat:@"%d Photos Selected",listSelected.count];

    }

}

- (void)gridView:(UIGridView*)gridView didLongPressCellAtIndex:(NSInteger)cellIndex
{
    
}

#pragma mark - Scroll View Delegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
//    [myGridView tileViews];
    DBLOG(@"did scroll");
    if (isMultipleSelection) {
        if (scrollView.contentOffset.y<44) {
            [scrollView scrollRectToVisible:CGRectMake(0, 
                                                       44, 
                                                       scrollView.frame.size.width, 
                                                       scrollView.frame.size.height) 
                                   animated:YES];
        }
    }
}

-(IBAction)btnWasClicked:(id)sender{
    DBLOG(@"btnwasclicked - %d",[sender tag]);
    [popUpBar.view setHidden:YES];
    UIButton * button = sender;
    UIActionSheet *actionSheet = nil;
    switch (button.tag) {
        case CameraButtonTag:
            if ([UIImagePickerController isSourceTypeAvailable:
                 UIImagePickerControllerSourceTypeCamera] == NO){
                return;
            }
            
            UIImagePickerController *cameraUI = [[UIImagePickerController alloc] init];
            cameraUI.sourceType = UIImagePickerControllerSourceTypeCamera;
            
            // Displays a control that allows the user to choose picture or
            // movie capture, if both are available:
            cameraUI.mediaTypes =
            [UIImagePickerController availableMediaTypesForSourceType:
             UIImagePickerControllerSourceTypeCamera];
            
            // Hides the controls for moving & scaling pictures, or for
            // trimming movies. To instead show the controls, use YES.
            cameraUI.allowsEditing = YES;
            
            cameraUI.delegate = self;
            
            //        cameraUI.mediaTypes = [[NSArray alloc] initWithObjects: (NSString *) kUTTypeImage, nil];
            
            [self presentModalViewController: cameraUI animated: YES];
            break;

        case EditButtonTag:
            [copyBtn setTitle:@"Copy"];
            textlb.title=[NSString stringWithFormat:@"0 Photos Selected"];
            
            if (!listSelected) {
                listSelected=[[NSMutableArray alloc] init];
            }
            [Utilities hideTabBar:self.tabBarController];
            [myGridView setFrame:CGRectMake(0, 44, 320, APP_SCREEN_HEIGHT-43-44)];
            for (NSNumber *index in listSelected) {
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            [listSelected removeAllObjects];
            
            isMultipleSelection = YES;
            [myGridView setEnableMultipleSelection:YES];
            [self.navigationController setNavigationBarHidden:YES animated:NO];
            [editBar setHidden:NO];
            [cancelNavBar setHidden:NO];
            [myGridView reloadData];
            break;
            
        case CancelButtonTag:
            [Utilities showTabBar:self.tabBarController];
            
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            
            for (NSNumber *index in listSelected) {
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            
            [listSelected removeAllObjects];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            [myGridView reloadData];
            break;
            
        case ShareButtonTag:
            actionSheet=[[UIActionSheet alloc] initWithTitle:nil 
                                                                   delegate:self 
                                                          cancelButtonTitle:@"Cancel" 
                                                     destructiveButtonTitle:nil 
                                                          otherButtonTitles:
                                        @"Export To Phone Gallery",
                                        @"Email",
                                        nil];
            [actionSheet setTag:ShareButtonTag];
            [actionSheet showInView:editBar];
            [actionSheet release];
            break;
            
        case CopyButtonTag:
            DBLOG(@"Copy and Messaging");
            UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
            NSMutableArray *listImage=[[NSMutableArray alloc] init];
            for (NSNumber *index in listSelected) {
                [listImage addObject:[self imageAtIndex:[index intValue]]];
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            [listSelected removeAllObjects];
            pasteboard.images=[listImage retain];
            
            [Utilities showTabBar:self.tabBarController];
            
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            [myGridView reloadData];
            break;
            
        case DeleteButtonTag:
            actionSheet=[[UIActionSheet alloc] initWithTitle:nil 
                                                    delegate:self 
                                           cancelButtonTitle:@"Cancel" 
                                      destructiveButtonTitle:@"Remove" 
                                           otherButtonTitles:nil];
            [actionSheet setTag:DeleteButtonTag];
            [actionSheet showInView:editBar];
            [actionSheet release];
            
        default:
            break;
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
    
    if ([actionSheet tag]==ShareButtonTag) {
        if (buttonIndex==0) {
            
            
            [Utilities showTabBar:self.tabBarController];
            for (NSNumber *index in listSelected) {
                UIImageWriteToSavedPhotosAlbum([self imageAtIndex:[index intValue]], nil,nil,nil);
                [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
            }
            
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];

            imageListArray = [[DatabaseConnection getFavoritePhotos] retain];
            self.navigationItem.title=[NSString stringWithFormat:@"Favorites (%d)",imageListArray.count];
            [myGridView reloadData];
            return;
        }
        if (buttonIndex==1) {
            
            [self sendMail];
            

            return;
        }
    }
    
    if ([actionSheet tag]==DeleteButtonTag) {
        if (buttonIndex==0) {
            
            DBLOG(@"Delete List:%@",listSelected);
            [Utilities showTabBar:self.tabBarController];
            isMultipleSelection = NO;
            [myGridView setEnableMultipleSelection:NO];
            [self.navigationController setNavigationBarHidden:NO animated:NO];
            [editBar setHidden:YES];
            [cancelNavBar setHidden:YES];
            NSMutableArray *itemArray=[[NSMutableArray alloc] init];
            
            for (NSNumber *index in listSelected) {
//                DBLOG(@"delete:%@",[NSURL URLWithString:[(Items*)[imageListArray objectAtIndex:[index intValue]] image]]);
                [itemArray addObject:[(Photo*)[imageListArray objectAtIndex:[index intValue]] itemObject]];
            }
            [DatabaseConnection deleteListItems:itemArray fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];
            [itemArray release];
            [listSelected removeAllObjects];
            imageListArray = [[DatabaseConnection getFavoritePhotos] retain];
            self.navigationItem.title=[NSString stringWithFormat:@"Favorite (%d)",imageListArray.count];
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            
            [myGridView reloadData];
            [myGridView scrollsToTop];

            return;
        }

    }
}

- (void) imagePickerControllerDidCancel: (UIImagePickerController *) picker {
    
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES 
                                 completion:^{
                                     DBLOG(@"done");
                                 }];
    }
    else {
        [self dismissModalViewControllerAnimated: YES];
        
    }    [picker release];
}

// For responding to the user accepting a newly-captured picture or movie
- (void) imagePickerController: (UIImagePickerController *) picker
 didFinishPickingMediaWithInfo: (NSDictionary *) info {
    [[LoadingView sharedInstance] showLoadingView];
    NSString *mediaType = [info objectForKey: UIImagePickerControllerMediaType];
    UIImage *originalImage, *editedImage, *imageToSave;
    
    // Handle a still image capture
    
//    if (CFStringCompare ((CFStringRef) mediaType, kUTTypeImage, 0) == kCFCompareEqualTo) {
    DBLOG(@"mediatype:%@",mediaType);
    if ([mediaType isEqualToString:@"public.image"]) {
        editedImage = (UIImage *) [info objectForKey:
                                   UIImagePickerControllerEditedImage];
        originalImage = (UIImage *) [info objectForKey:
                                     UIImagePickerControllerOriginalImage];

        if (editedImage) {
            imageToSave = editedImage;
        } else {
            imageToSave = originalImage;
        }  
    }
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    
    NSString *targetPath=[[documentPath stringByAppendingPathComponent:@"Favorites"] retain];
    
    NSFileManager *fm=[[[NSFileManager alloc] init] autorelease];
    [fm createFileAtPath:[targetPath stringByAppendingPathComponent:[NSString stringWithFormat:@"%@_T.png", [Utilities uniqueStringWithPrefix:@"F"] ]] 
                contents: UIImagePNGRepresentation(imageToSave)
              attributes:nil];
    if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(@"5.0")) {
        [self dismissViewControllerAnimated:YES 
                                 completion:^{
                                     DBLOG(@"done");
                                     [[LoadingView sharedInstance] stopLoadingView];

                                 }];
    }
    else {
        [[LoadingView sharedInstance] stopLoadingView];
        [self dismissModalViewControllerAnimated: YES];

    }
    [picker release];
    
}


- (UIImage *)imageAtIndex:(NSUInteger)index {

    DBLOG(@"PhotoViewController - imageAtIndex:%d",index);
    Photo *photo = [imageListArray objectAtIndex:index];
    
    NSString *documentPath=[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
    NSString *targetPath= nil;
    
    targetPath=[documentPath retain];
    if ([[NSFileManager defaultManager] fileExistsAtPath:[targetPath stringByAppendingPathComponent:[photo.photoImage lastPathComponent]]]) {
        return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[[photo photoImage] lastPathComponent]]];
    }else{
        return [UIImage imageWithContentsOfFile:[targetPath stringByAppendingPathComponent:[[photo photoThumbnail] lastPathComponent]]];
    }
    
}
#pragma mark - Mail Controller

-(void)sendMail{
    
    if ([MFMailComposeViewController canSendMail]) {
        
        // Fill out the email body text
        //Create a string with HTML formatting for the email body
        NSString *iTunesLink = @"itms-apps://itunes.com/apps/reacticons"; // replate it with yours
        NSString *emailBody =
        [NSString stringWithFormat:@"\n<p>Sent from Reacticons! ...an gallery app of all reaction images.</br> <a href = '%@'>Download</a> it now!</p>", iTunesLink];
        MFMailComposeViewController *emailDialog = [[MFMailComposeViewController alloc] init];
        emailDialog.mailComposeDelegate = self;
//        [emailDialog setSubject:@"My Inline Image Document"];
        [emailDialog setMessageBody:emailBody isHTML:YES];
        
        //Pick an image to insert
        //This example would come from the main bundle, but your source can be elsewhere
        for (NSNumber *index in listSelected) {
            
            UIImage *emailImage = [self imageAtIndex:[index intValue]];

            NSData *imageData = [NSData dataWithData:UIImagePNGRepresentation(emailImage)];

            [emailDialog addAttachmentData:imageData mimeType:@"png" fileName:[[(Photo*)[imageListArray objectAtIndex:[index intValue]] photoThumbnail] lastPathComponent]];

        }

        //You could repeat here with more text or images, otherwise
        //close the HTML formatting
//        DBLOG(@"%@",emailBody);
        
        //Create the mail composer window

        [self presentModalViewController:emailDialog animated:YES];
        [emailDialog release];

        
    }
    else {
        
        UIAlertView *alert =[[UIAlertView alloc] initWithTitle:@"Cannot Send Via Mail" message:@"Please setup your mail before share via Email" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    for (NSNumber *index in listSelected) {
        [[myGridView cellAtIndex:[index intValue]] setIsSelected:NO];
    }
    [listSelected removeAllObjects];

  
    
}
-(void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error {

    [controller dismissViewControllerAnimated:YES completion:^{
        isMultipleSelection = NO;
        [myGridView setEnableMultipleSelection:NO];
        [self.navigationController setNavigationBarHidden:NO animated:NO];
        [editBar setHidden:YES];
        [cancelNavBar setHidden:YES];
        [myGridView reloadData];
    }];

}


#pragma mark - POPUP Delegate

- (void)popUpBar:(PopUpViewController *)popUpController didSelectButton:(id)sender
{
    
    [self popupDidSelectBtnTag:[sender tag]];
    [popUpBar.view setHidden:YES];
}

-(void)popupDidSelectBtnTag:(int)tag{
    [[LoadingView sharedInstance] stopLoadingView];
    
    DBLOG(@"popupDidSelectBtnTag:%d",tag);
    
    switch (tag) {
        case 0:
            DBLOG(@"Share");
            NSString *stringURL = @"sms:";
            NSURL *url = [NSURL URLWithString:stringURL];
            [[UIApplication sharedApplication] openURL:url]; 
            break;
            
        case 1:
            
            [DatabaseConnection deleteListItems:[NSMutableArray arrayWithObject:[[imageListArray objectAtIndex:selectedCellIndex] itemObject]] fromEntity:@"ManagedFavoritePhoto" withPrimaryKey:@"photoID"];

            [listSelected removeAllObjects];
            imageListArray = [[DatabaseConnection getFavoritePhotos] retain];
            self.navigationItem.title=[NSString stringWithFormat:@"Favorite (%d)",imageListArray.count];
            [myGridView setFrame:CGRectMake(0, 0, 320, APP_SCREEN_HEIGHT-43-44)];
            
            [myGridView reloadData];
            [myGridView scrollsToTop];
            
            break;
            
        case 2:
            DBLOG(@"View detail");
            ImageDetailViewController * detailView = [[ImageDetailViewController alloc] init];
            [detailView setItemList:[imageListArray mutableCopy]];
            [detailView setItemIndex:selectedCellIndex];
            [detailView setItemType:@"favorite"];
            [detailView setHidesBottomBarWhenPushed:YES];
            self.navigationItem.title=@"Back";
            [self.navigationController pushViewController:detailView animated:YES];
            [detailView release];

            break;
            
        default:
            break;
    }
    if (tag==3) {
        MemeCreatorViewController *mcvc=[[MemeCreatorViewController alloc] init];
        [mcvc setImage:[self imageAtIndex:selectedCellIndex]];
        [self presentModalViewController:mcvc animated:YES];
    }
}

#pragma mark - Download All List

-(void)downloadAllPhotos{
    NSString *documentPath=[NSHomeDirectory() stringByAppendingPathComponent:@"Documents"];
    for (Photo *photo in imageListArray) {
        if (![[NSFileManager defaultManager] fileExistsAtPath:[documentPath stringByAppendingPathComponent:[photo.photoImage lastPathComponent]]]) {
            DBLOG(@"Download:%@",photo.photoImage);

            DownloadHelper * downloadHelper = [[DownloadHelper alloc] init];
            [downloadHelper downloadFile:[[photo photoImage] lastPathComponent]
                        toFolderWithName:nil
                                 withURL:[NSURL URLWithString:[photo photoImage]]
                  andSuccessNotification:nil
                     andFailNotification:nil];
        }
    }
}

@end

